package com.woniuxy.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.PaperCategory;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.IPaperCategoryService;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author ylr
 * @time 2022/06/02 17:31:42
 */
@RestController
@RequestMapping("paperCategory")
public class PaperCategoryController {

    @Autowired
    IPaperCategoryService paperCategoryService;

    @RequestMapping("list/{currentPage}/{pageSize}")
    public ResponseEntity findCategories(@PathVariable int currentPage, @PathVariable int pageSize, @RequestBody String jsonString){
        //初始化一个hashmap
        Map<String, Object> map = new HashMap<>();
        //将json字符串转换为json对象
        JSONObject json = JSONObject.parseObject(jsonString);
        //将json对象循环转换为map
        Iterator it = json.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            if (entry.getValue().toString().length() == 0){
                map.put(entry.getKey(), null);
            }else {
                map.put(entry.getKey(), entry.getValue());
            }
        }
        PageHelper.startPage(currentPage, pageSize);
        PageInfo<PaperCategory> paperCategoryPageInfo = new PageInfo<>(paperCategoryService.findCategories(map));
        return new ResponseEntity(paperCategoryPageInfo);
    }

    @RequestMapping("add")
    public ResponseEntity addCategory(@RequestBody PaperCategory paperCategory){
        if(paperCategoryService.addCategory(paperCategory)){
            return ResponseEntity.SUCCESS;
        }
        return ResponseEntity.ERROR;
    }

    @RequestMapping("del/{id}")
    public ResponseEntity delCategory(@PathVariable Integer id){
        if(paperCategoryService.delCategory(id)){
            return ResponseEntity.SUCCESS;
        }
        return ResponseEntity.ERROR;
    }

    @RequestMapping("grades")
    public ResponseEntity findGrades(){
        return new ResponseEntity(paperCategoryService.findGrades());
    }

    //树形菜单查询
    @RequestMapping("treelist")
    public ResponseEntity findInventories(){
        return new ResponseEntity(paperCategoryService.findCategories());
    }
}
